#include "mainwindow.h"
#include "globalconfig.h"
#include "settings.h"

#include <QActionGroup>
#include <QScreen>
#include <QDebug>


MainWindow::MainWindow(QWidget *parent)
    : AMainWindow{parent}
{
    resize(1680, 900);

    widget = new MainWidget(this);

    setCentralWidget(widget);
    setFocusPolicy(Qt::ClickFocus);

    auto menuBar = this->menuBar();

    auto fileMenu = menuBar->addMenu(tr("File (&F)"));

    auto vdAct = new QAction(tr("Create Virtual Device"), this);
    fileMenu->addAction(vdAct);

    fileMenu->addSeparator();

    auto exitAct = new QAction(tr("Exit (&E)"), this);
    fileMenu->addAction(exitAct);

    auto languageMenu = menuBar->addMenu(tr("Language (&L)"));
    languageMenu->setToolTipsVisible(true);

    auto languageGroup = new QActionGroup(this);

    auto englishAct = new QAction("English (" ENGLISH ")", this);
    englishAct->setCheckable(true);
    englishAct->setToolTip("Take effect after reboot.");
    languageMenu->addAction(englishAct);
    languageGroup->addAction(englishAct);

    auto zhCnAct = new QAction("简体中文 (" SIMPLIFIED_CHINESE ")", this);
    zhCnAct->setCheckable(true);
    zhCnAct->setToolTip("重启后生效。");
    languageMenu->addAction(zhCnAct);
    languageGroup->addAction(zhCnAct);

    auto systemMenu = menuBar->addMenu(tr("System (&S)"));

    auto logoAct = new QAction(tr("Update Logo"), this);
    systemMenu->addAction(logoAct);

    systemMenu->addSeparator();

    auto updateAct = new QAction(tr("Check For Updates"), this);
    systemMenu->addAction(updateAct);

    systemMenu->addSeparator();

    auto helpMenu = menuBar->addMenu(tr("Help (&H)"));

    auto contactAct = new QAction(tr("Contact Information"), this);
    helpMenu->addAction(contactAct);

    helpMenu->addSeparator();

    auto aboutAct = new QAction(tr("About"), this);
    helpMenu->addAction(aboutAct);

    QSettings settings(ORGANIZATION_NAME, APPLICATION_NAME);
    auto language = settings.value(LANGUAGE, ENGLISH).toString();
    if (language == SIMPLIFIED_CHINESE) {
        zhCnAct->setChecked(true);
    }
    else {
        englishAct->setChecked(true);
    }

    connect(vdAct, &QAction::triggered, widget, &MainWidget::createVirtualDevice);

    connect(exitAct, &QAction::triggered, this, &MainWindow::close);

    connect(logoAct, &QAction::triggered, widget, &MainWidget::setLogo);

    connect(languageGroup, &QActionGroup::triggered, this, [=](QAction *action) {
        QSettings settings(ORGANIZATION_NAME, APPLICATION_NAME);
        if (action == zhCnAct) {
            settings.setValue(LANGUAGE, SIMPLIFIED_CHINESE);
        }
        else {
            settings.setValue(LANGUAGE, ENGLISH);
        }
    });
}

void MainWindow::closeEvent(QCloseEvent *event)
{
    GlobalConfig::getInstance().windowClosed();
    event->accept();
}
